#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2023/1/1 20:04
# @Author  : Xudong Geng
# @File    : mail.py
# @Software: PyCharm

import smtplib
from email.message import EmailMessage
import os
from os.path import dirname, abspath, join
from dotenv import load_dotenv

# Define Path Variables
## Env variable file(.env) will be injected by vault
path = join(dirname(abspath(__file__)), 'config/.env')
load_dotenv(path)

# Define Environment Variables
user = os.getenv('MailUser')
password = os.getenv('MailPassword')
smtpsrv = os.getenv('MailServer')
smtpserver = smtplib.SMTP(smtpsrv,os.getenv('MailServerPort'))
mailbodyfile = os.getenv('MailBodyFile')

# Check environment variables
print('Mail Body File Path: %s' %(path))

# Load mail body from mail body file
## Mail body file created by argo workflow
with open(mailbodyfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# Environment variables
CommitEmail = os.getenv('commitemail')
AuthorEmail = os.getenv('authoremail')
MailTo = os.getenv('MailTo')

# Mail receivers
if CommitEmail:
    print(CommitEmail)
    MailTo = MailTo.join(CommitEmail, ',')
if AuthorEmail:
    print(AuthorEmail)
    MailTo = MailTo.join(AuthorEmail, ',')
print('========================================')
print('Mail Former List: %s type: %s' %(MailTo,type(MailTo)))
print('========================================')


# Mail address filter
## Mail receiver address is collected from git commit informaiton and github webhook request body.
## If the mail receiver address is not ended with @appen.com, will be ignored.
Mails = MailTo.split(',')
print('middle mail list: %s' %(Mails))
MailList = set()
st = ''

for item in Mails:
    if str(item).endswith('@appen.com'):
        MailList.add(item)
print('Total Mail List: %s' %(MailList))

for item in MailList:
    item.strip('"').strip("'")
    st += item + ','
MailAddrList = st.strip(',').strip("'").strip('"')


# Mail subject
with open(mailbodyfile, 'r') as f:
    for line in f:
        if line.startswith('Release Status'):
            ReleaseStats = line.split(':')[1].strip()
if ReleaseStats == 'Succeeded':
    MailSubject = os.getenv('MailSubject') + ' ' + 'Successfully'
else:
    MailSubject = os.getenv('MailSubject') + ' ' + 'Failed'


# Mail Information
print('Send mail information:')
print("Mail Subject: %s \nMail From: %s \nMail To: %s \n Release Status: %s" %(MailSubject,os.getenv('MailFrom'),MailAddrList,ReleaseStats))

msg['Subject'] = MailSubject
msg['From'] = os.getenv('MailFrom')
msg['To'] = MailAddrList

# Send Email Message
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.login(user, password)
smtpserver.send_message(msg)
smtpserver.close()